package com.insta.java.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.insta.java.model.User;

@Repository("userDao")
public class UserDao implements IUserDao {

	private SessionFactory sessionFactory;
	
	@Autowired
	public UserDao(SessionFactory sessionFactory){
		super();
		this.sessionFactory= sessionFactory;
	}
	
	
	public Session getSession(){
		return sessionFactory.getCurrentSession();
	}
	
	public void closeSession(){
		sessionFactory.close();
	}
	
	public void save(User user) {
		Session session= getSession();
		Transaction tx=null;
		try{
			tx= session.beginTransaction();
			session.save(user);
			tx.commit();
		}catch (RuntimeException e) {
			if(tx!=null){
				tx.rollback();
			}
			throw e;
		}
	}

	public void update(User user) {
		Session session= getSession();
		Transaction tx=null;
		try{
			tx= session.beginTransaction();
			session.update(user);
			tx.commit();
		}catch (RuntimeException e) {
			if(tx!=null){
				tx.rollback();
			}
			throw e;
		}
		
	}

	public void delete(User user) {
		Session session= getSession();
		Transaction tx=null;
		try{
			tx= session.beginTransaction();
			session.delete(user);
			tx.commit();
		}catch (RuntimeException e) {
			if(tx!=null){
				tx.rollback();
			}
			throw e;
		}
	}

	@SuppressWarnings("unchecked")
	public User findByLogin(String login) {
		Session session = getSession();
		Transaction tx=null;
		try{
			tx= session.beginTransaction();
			Query query = session.createQuery("from User where login=?");
			query.setString(0, login);
			List<User> list = query.list();
			tx.commit();
			if(list.size()==1){
				return list.get(0);
			}else{
				return null;
			}
		}catch (RuntimeException e) {
			if(tx!=null){
				tx.rollback();
			}
			throw e;
		}
	}

}
